package fh.app4stud.mensa;

import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import fh.app4stud.mensa.data.RestaurantLocation;
import fh.app4stud.mensa.database.MenuDbAdapter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

/**
 * Service that provides a list of all the locations
 *
 * Created by IntelliJ IDEA.
 * User: ivan plese
 * Date: 22.04.11
 * Time: 00:35
 * To change this template use File | Settings | File Templates.
 */
public class MensaLocationService extends Service {

    //varibles
    ArrayList<RestaurantLocation> restaurantLocations;
    private final IBinder locationServiceBinder;
    private MenuDbAdapter menuDbHelper;

    private final String TAG = "LOCATION SERVICE TAG";

    public MensaLocationService() {
        locationServiceBinder = new LocalBinder();
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "Creating LOCATION Service**********************************************");
        restaurantLocations = new ArrayList<RestaurantLocation>();

        menuDbHelper = new MenuDbAdapter(this);
        menuDbHelper.open();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return locationServiceBinder;
    }

    public class LocalBinder extends Binder {
        public MensaLocationService getLocationService(){
            Log.i(TAG, "Returning the service");
            return MensaLocationService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        try {

            String myFeed = getString(fh.app4stud.mensa.R.string.my_feed);
            URL url = new URL(myFeed);
            Log.i(TAG, "url opend");
            URLConnection connection = url.openConnection();

            int responseCode = -1;
            HttpURLConnection httpConnection = null;
            int iRetry = 0;

            while (iRetry < 10) {
                iRetry++;
                try {
                    httpConnection = (HttpURLConnection) connection;
                    httpConnection.setConnectTimeout(3000);
                    httpConnection.setDoInput(true);
                    httpConnection.connect();
                    responseCode = httpConnection.getResponseCode();
                } catch (IOException e) {
                    e.printStackTrace();
                    responseCode = -1;
                }
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    iRetry = 10;
                    Log.i(TAG, "If it came to here web service is working");
                    InputStream in = httpConnection.getInputStream();

                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

                    Document dom = documentBuilder.parse(in);
                    Element documentElement = dom.getDocumentElement();

                    addAllLocations(documentElement);
                } else {
                    iRetry = 10;
                    Resources myResources = getResources();
                    InputStream inputStream = myResources.openRawResource(R.raw.locations);
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                    Document document = documentBuilder.parse(inputStream);
                    Element documentElement = document.getDocumentElement();
                    addAllLocations(documentElement);
                }
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } finally {
        }

        return Service.START_NOT_STICKY;
    }

    private void addAllLocations(Element documentElement) {
        Log.i(TAG, "In add all locations");
        NodeList nodeList = documentElement.getElementsByTagName("location");

        if (nodeList != null && nodeList.getLength() > 0) {

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element location;
                location = (Element) nodeList.item(i);
                Element city = (Element) location.getElementsByTagName("city").item(0);
                Element houseNumber = (Element) location.getElementsByTagName("houseNumber").item(0);
                Element locationName = (Element) location.getElementsByTagName("locationName").item(0);
                Element street = (Element) location.getElementsByTagName("street").item(0);
                Element zipCode = (Element) location.getElementsByTagName("zipCode").item(0);
                Element latitude = (Element) location.getElementsByTagName("latitude").item(0);
                Element longitude = (Element) location.getElementsByTagName("longitude").item(0);
                Log.i(TAG, "getting the node values to str and doubles");

                String _locationName = locationName.getFirstChild().getNodeValue();
                String _city = city.getFirstChild().getNodeValue();
                String _streetName = street.getFirstChild().getNodeValue();
                int _houseNumber = Integer.parseInt(houseNumber.getFirstChild().getNodeValue());
                int ZIPCode = Integer.parseInt(zipCode.getFirstChild().getNodeValue());
                float _latitude = Float.parseFloat(latitude.getFirstChild().getNodeValue());
                float _longitude = Float.parseFloat(longitude.getFirstChild().getNodeValue());

                Log.i(TAG, "inserting in location table: " + " | " + _locationName + " | " + _city + " | " + _streetName + " | " + _houseNumber + " | " + ZIPCode + " | " + _latitude + " | " + _longitude);
                menuDbHelper.createLocation(_locationName, _city, _streetName, _houseNumber, ZIPCode, _latitude, _longitude);
                           //createLocation( String loc_name, String city, String street, int house_nr, int zip, float lat, float lon )

            }
        }
    }
}
